using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
using Work.Domain;

namespace WinFormsApp1
{
    public partial class AppointmentForm : Form
    {
        private int? _patientId;
        private const string ApiBaseUrl = "http://localhost:5044";

        /// <summary>
        /// 科室与医生的对应关系字典
        /// 每个科室至少配置2个医生，符合实际医院场景
        /// </summary>
        private readonly Dictionary<string, List<string>> _deptDoctorMap = new Dictionary<string, List<string>>
        {
            ["心血管内科"] = new List<string> { "张叁叁", "赵强" },
            ["骨科"] = new List<string> { "李偲偲", "孙丽华" },
            ["妇产科"] = new List<string> { "姜稳稳", "钱芳" },
            ["儿科"] = new List<string> { "贾樟柯", "刘娜" },
            ["眼科"] = new List<string> { "王武武", "郑伟" },
            ["口腔科"] = new List<string> { "周建国", "何敏" },
            ["皮肤科"] = new List<string> { "吴明", "林晓燕" },
            ["中医科"] = new List<string> { "陈俊杰", "徐国栋" },
            ["急诊科"] = new List<string> { "黄志伟", "马静", "张叁叁" }  // 急诊科配3个医生
        };

        public AppointmentForm()
        {
            InitializeComponent();
            BindEnums();
            // 注册科室选择变化事件
            cmbDept.SelectedIndexChanged += CmbDept_SelectedIndexChanged;
        }

        private void BindEnums()
        {
            // 绑定科室下拉框
            cmbDept.Items.Clear();
            foreach (var name in Enum.GetNames(typeof(Departmentsel)))
            {
                cmbDept.Items.Add(name);
            }
            
            // 绑定号类型下拉框
            cmbType.Items.Clear();
            foreach (var name in Enum.GetNames(typeof(AppointmentTypesel)))
            {
                cmbType.Items.Add(name);
            }
            
            // 设置默认值
            if (cmbDept.Items.Count > 0) cmbDept.SelectedIndex = 0;
            if (cmbType.Items.Count > 0) cmbType.SelectedIndex = 0;
        }

        /// <summary>
        /// 科室选择变化事件：根据选择的科室加载对应的医生
        /// </summary>
        private void CmbDept_SelectedIndexChanged(object? sender, EventArgs e)
        {
            cmbDoctor.Items.Clear();
            
            var selectedDept = cmbDept.SelectedItem?.ToString();
            if (string.IsNullOrEmpty(selectedDept))
            {
                return;
            }

            // 根据科室获取对应的医生列表
            if (_deptDoctorMap.ContainsKey(selectedDept))
            {
                foreach (var doctor in _deptDoctorMap[selectedDept])
                {
                    cmbDoctor.Items.Add(doctor);
                }
                
                // 自动选择第一个医生
                if (cmbDoctor.Items.Count > 0)
                {
                    cmbDoctor.SelectedIndex = 0;
                }
            }
            else
            {
                // 如果该科室没有配置医生，显示提示
                MessageBox.Show($"该科室暂无医生可选", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private async void btnQuery_Click(object? sender, EventArgs e)
        {
            _patientId = null;
            txtName.Text = string.Empty;
            txtIdCard.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtGender.Text = string.Empty;
            txtBirthday.Text = string.Empty;

            var card = txtCard.Text?.Trim();
            if (string.IsNullOrWhiteSpace(card))
            {
                MessageBox.Show("请输入卡号", "提示");
                return;
            }

            try
            {
                using var http = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
                var resp = await http.GetAsync($"api/Patient/GetByCard?cardNumber={Uri.EscapeDataString(card)}");
                resp.EnsureSuccessStatusCode();
                var json = await resp.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResultPatient>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
                if (result != null && result.Code == 100 && result.Data != null)
                {
                    _patientId = result.Data.PatientId;
                    txtName.Text = result.Data.PatientName;
                    txtIdCard.Text = result.Data.IdCard;
                    txtPhone.Text = result.Data.Phone;
                    txtGender.Text = result.Data.Gender ? "男" : "女";
                    txtBirthday.Text = result.Data.Birthday?.ToString("yyyy-MM-dd") ?? string.Empty;
                }
                else
                {
                    MessageBox.Show(result?.Message ?? "未找到就诊人，请先办理就诊卡", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}");
            }
        }

        private async void btnSubmit_Click(object? sender, EventArgs e)
        {
            if (_patientId == null)
            {
                MessageBox.Show("请先通过卡号查询就诊人", "提示");
                return;
            }
            var req = new CreateAppointmentRequest
            {
                PatientId = _patientId.Value,
                CardNumber = txtCard.Text?.Trim(),
                AppointmentType = cmbType.SelectedItem?.ToString(),
                DoctorName = cmbDoctor.SelectedItem?.ToString(),
                Department = cmbDept.SelectedItem?.ToString(),
                RegistrationFee = decimal.TryParse(txtRegFee.Text, out var rf) ? rf : null,
                OtherFee = decimal.TryParse(txtOtherFee.Text, out var ofe) ? ofe : null,
                RegistrationDate = dpRegDate.Value,
                VisitDate = dpVisitDate.Value
            };

            try
            {
                using var http = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
                var body = JsonSerializer.Serialize(req);
                using var content = new StringContent(body, Encoding.UTF8, "application/json");
                var resp = await http.PostAsync("api/Appointment/Create", content);
                resp.EnsureSuccessStatusCode();
                var json = await resp.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResultInt>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
                if (result != null && result.Code == 100)
                {
                    MessageBox.Show("挂号成功", "成功");
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show(result?.Message ?? "挂号失败", "错误");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"挂号失败：{ex.Message}");
            }
        }

        private class ApiResultPatient
        {
            public int Code { get; set; }
            public string? Message { get; set; }
            public PatientDto? Data { get; set; }
        }
        private class PatientDto
        {
            public int PatientId { get; set; }
            public string? PatientName { get; set; }
            public string? IdCard { get; set; }
            public string? Phone { get; set; }
            public bool Gender { get; set; }
            public DateTime? Birthday { get; set; }
        }
        private class CreateAppointmentRequest
        {
            public int PatientId { get; set; }
            public string? CardNumber { get; set; }
            public string? AppointmentType { get; set; }
            public string? DoctorName { get; set; }
            public string? Department { get; set; }
            public decimal? RegistrationFee { get; set; }
            public decimal? OtherFee { get; set; }
            public DateTime? RegistrationDate { get; set; }
            public DateTime? VisitDate { get; set; }
        }
        private class ApiResultInt
        {
            public int Code { get; set; }
            public string? Message { get; set; }
            public int Data { get; set; }
        }
    }
}




